package com.bestcem.xm.txtanls.controller;

import cn.hutool.core.lang.Validator;
import com.alibaba.excel.EasyExcelFactory;
import com.bestcem.xm.common.core.constant.Constants;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.txtanls.controller.convert.ChartExportConvert;
import com.bestcem.xm.txtanls.controller.param.chart.*;
import com.bestcem.xm.txtanls.entity.pojo.TopicDO;
import com.bestcem.xm.txtanls.entity.pojo.ViewpointDO;
import com.bestcem.xm.txtanls.enums.EmotionTagEnum;
import com.bestcem.xm.txtanls.grpc.service.param.chart.*;
import com.bestcem.xm.txtanls.service.ChartService;
import com.bestcem.xm.txtanls.service.TopicService;
import com.bestcem.xm.txtanls.service.ViewpointService;
import com.bestcem.xm.txtanls.service.dto.chart.*;
import com.bestcem.xm.txtanls.util.ChartUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

/**
 * 文本分析图表导出
 *
 * @author jy.zhao
 * @version 2.0
 * @date 2021/8/5 17:19
 **/
@Api(tags = "文本分析图表导出接口")
@Controller
@RequestMapping(value = "/txtanls/chart_export", produces = MediaType.APPLICATION_JSON_VALUE)
@Slf4j
public class ChartExportController {

    @Autowired
    private ChartService chartService;
    @Autowired
    private ViewpointService viewpointService;
    @Autowired
    private TopicService topicService;

    @ApiOperation(value = "总体情感细分导出")
    @GetMapping(value = "/emotion_detail")
    public void emotionDetail(@RequestParam(value = "project_id") String projectId,
                              @RequestParam(value = "field_id", required = false) String fieldId,
                              @RequestParam(value = "dtfiltertype", required = false) String filterType,
                              @RequestParam(value = "current", required = false) String current,
                              @RequestParam(value = "start_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
                              @RequestParam(value = "end_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
                              HttpServletResponse response) {
        BaseChartQuery baseChartQuery = new BaseChartQuery(projectId, fieldId, filterType, current, startTime, endTime);
        BaseChartParam baseChartParam = baseChartQuery.getBaseChartParam();
        String errorMessage = ChartValid.validBaseChartParam(baseChartParam);
        if (Validator.isNotNull(errorMessage)) {
            ChartUtil.excelErrorResponse(response, 4, errorMessage, Constants.TXTANLS_MODEL_NAME);
            return;
        }
        ServiceResult<EmotionDetailDTO> serviceResult = chartService.statEmotion(baseChartParam);
        List<List<Object>> excelData = ChartExportConvert.emotionDetailToExcelData(serviceResult.getData(), baseChartQuery.getInterval().getIndex());
        try {
            response.setContentType(Constants.EXCEL_CONTENT_TYPE);
            String fileName = URLEncoder.encode(ChartExportConvert.EMOTION_DETAIL_FILE_NAME, Constants.UTF_8);
            response.setHeader(ChartExportConvert.EXCEL_RESPONSE_HEADER_KEY, String.format(ChartExportConvert.EXCEL_RESPONSE_HEADER_VALUE, fileName));
            EasyExcelFactory.write(response.getOutputStream()).autoCloseStream(Boolean.FALSE).sheet().doWrite(excelData);
        } catch (Exception e) {
            log.error("[Txtanls] 图表总体情感细分导出失败: 参数:{}", baseChartParam, e);
            ChartUtil.excelErrorResponse(response, 5, "图表总体情感细分导出失败", Constants.TXTANLS_MODEL_NAME);
        }
    }

    @ApiOperation(value = "总体情感标签导出")
    @GetMapping(value = "/emotion_tag")
    public void emotionTag(@RequestParam(value = "project_id") String projectId,
                           @RequestParam(value = "field_id", required = false) String fieldId,
                           @RequestParam(value = "dtfiltertype", required = false) String filterType,
                           @RequestParam(value = "current", required = false) String current,
                           @RequestParam(value = "type", required = true) Integer type,
                           @RequestParam(value = "start_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
                           @RequestParam(value = "end_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
                           HttpServletResponse response) {
        if (type != EmotionTagEnum.CUSTOMER_FEEDBACK.getIndex() && type != EmotionTagEnum.POSITIVE_EMOTION.getIndex() && type != EmotionTagEnum.NEGATIVE_EMOTION.getIndex()) {
            ChartUtil.excelErrorResponse(response, 4, "导出情感标签类型不符合要求", Constants.TXTANLS_MODEL_NAME);
        }
        BaseChartQuery baseChartQuery = new BaseChartQuery(projectId, fieldId, filterType, current, startTime, endTime);
        BaseChartParam baseChartParam = baseChartQuery.getBaseChartParam();
        String errorMessage = ChartValid.validBaseChartParam(baseChartParam);
        if (Validator.isNotNull(errorMessage)) {
            ChartUtil.excelErrorResponse(response, 4, errorMessage, Constants.TXTANLS_MODEL_NAME);
            return;
        }
        ServiceResult<EmotionDetailDTO> serviceResult = chartService.statEmotion(baseChartParam);
        String fileNameStr;
        if (type == EmotionTagEnum.CUSTOMER_FEEDBACK.getIndex()) {
            fileNameStr = ChartExportConvert.EMOTION_TAG_FEEDBACK_FILE_NAME;
        } else if (type == EmotionTagEnum.POSITIVE_EMOTION.getIndex()) {
            fileNameStr = ChartExportConvert.EMOTION_TAG_POSITIVE_FILE_NAME;
        } else {
            fileNameStr = ChartExportConvert.EMOTION_TAG_NEGATIVE_FILE_NAME;
        }
        List<List<Object>> excelData = ChartExportConvert.emotionTagToExcelData(serviceResult.getData(), type);
        try {
            response.setContentType(Constants.EXCEL_CONTENT_TYPE);
            String fileName = URLEncoder.encode(fileNameStr, Constants.UTF_8);
            response.setHeader(ChartExportConvert.EXCEL_RESPONSE_HEADER_KEY, String.format(ChartExportConvert.EXCEL_RESPONSE_HEADER_VALUE, fileName));
            EasyExcelFactory.write(response.getOutputStream()).autoCloseStream(Boolean.FALSE).sheet().doWrite(excelData);
        } catch (Exception e) {
            log.error("[Txtanls] 图表总体情感标签导出失败: 参数:{}, 类型: {}", baseChartParam, type, e);
            ChartUtil.excelErrorResponse(response, 5, "图表总体情感标签导出失败", Constants.TXTANLS_MODEL_NAME);
        }
    }

    @ApiOperation(value = "总体情感趋势导出")
    @GetMapping(value = "/emotion_trend")
    public void emotionTrend(@RequestParam(value = "project_id") String projectId,
                             @RequestParam(value = "field_id", required = false) String fieldId,
                             @RequestParam(value = "dtfiltertype", required = false) String filterType,
                             @RequestParam(value = "current", required = false) String current,
                             @RequestParam(value = "start_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
                             @RequestParam(value = "end_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
                             HttpServletResponse response) {
        BaseChartQuery baseChartQuery = new BaseChartQuery(projectId, fieldId, filterType, current, startTime, endTime);
        BaseChartParam baseChartParam = baseChartQuery.getBaseChartParam();
        String errorMessage = ChartValid.validBaseChartParam(baseChartParam);
        if (Validator.isNotNull(errorMessage)) {
            ChartUtil.excelErrorResponse(response, 4, errorMessage, Constants.TXTANLS_MODEL_NAME);
            return;
        }
        ServiceResult<List<EmotionDTO>> serviceResult = chartService.statEmotionTrend(baseChartParam);
        List<List<Object>> excelData = ChartExportConvert.emotionToExcelData(serviceResult.getData(), baseChartQuery.getInterval().getIndex());
        try {
            response.setContentType(Constants.EXCEL_CONTENT_TYPE);
            String fileName = URLEncoder.encode(ChartExportConvert.EMOTION_TREND_FILE_NAME, Constants.UTF_8);
            response.setHeader(ChartExportConvert.EXCEL_RESPONSE_HEADER_KEY, String.format(ChartExportConvert.EXCEL_RESPONSE_HEADER_VALUE, fileName));
            EasyExcelFactory.write(response.getOutputStream()).autoCloseStream(Boolean.FALSE).sheet().doWrite(excelData);
        } catch (Exception e) {
            log.error("[Txtanls] 图表总体情感趋势导出失败: 参数:{}", baseChartParam, e);
            ChartUtil.excelErrorResponse(response, 5, "图表总体情感趋势导出失败", Constants.TXTANLS_MODEL_NAME);
        }
    }

    @ApiOperation(value = "观点统计")
    @GetMapping(value = "/viewpoint_stat")
    public void viewpointStat(@RequestParam(value = "project_id") String projectId,
                              @RequestParam(value = "field_id", required = false) String fieldId,
                              @RequestParam(value = "dtfiltertype", required = false) String filterType,
                              @RequestParam(value = "current", required = false) String current,
                              @RequestParam(value = "start_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
                              @RequestParam(value = "end_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
                              HttpServletResponse response) {
        BaseChartQuery baseChartQuery = new BaseChartQuery(projectId, fieldId, filterType, current, startTime, endTime);
        BaseChartParam baseChartParam = baseChartQuery.getBaseChartParam();
        String errorMessage = ChartValid.validBaseChartParam(baseChartParam);
        if (Validator.isNotNull(errorMessage)) {
            ChartUtil.excelErrorResponse(response, 4, errorMessage, Constants.TXTANLS_MODEL_NAME);
            return;
        }
        ServiceResult<ViewpointStatResultDTO> serviceResult = chartService.statViewpoint(baseChartParam);
        List<List<Object>> excelData = ChartExportConvert.viewpointGroupStatToExcelData(serviceResult.getData().getViewPointGroupStatDTOS());
        try {
            response.setContentType(Constants.EXCEL_CONTENT_TYPE);
            String fileName = URLEncoder.encode(ChartExportConvert.VIEWPOINT_STAT_FILE_NAME, Constants.UTF_8);
            response.setHeader(ChartExportConvert.EXCEL_RESPONSE_HEADER_KEY, String.format(ChartExportConvert.EXCEL_RESPONSE_HEADER_VALUE, fileName));
            EasyExcelFactory.write(response.getOutputStream()).autoCloseStream(Boolean.FALSE).sheet().doWrite(excelData);
        } catch (Exception e) {
            log.error("[Txtanls] 图表观点统计导出失败: 参数:{}", baseChartParam, e);
            ChartUtil.excelErrorResponse(response, 5, "图表观点统计导出失败", Constants.TXTANLS_MODEL_NAME);
        }
    }

    @ApiOperation(value = "观点top5")
    @GetMapping(value = "/viewpoint_top")
    public void viewpointStat(@RequestParam(value = "project_id") String projectId,
                              @RequestParam(value = "field_id", required = false) String fieldId,
                              @RequestParam(value = "dtfiltertype", required = false) String filterType,
                              @RequestParam(value = "current", required = false) String current,
                              @RequestParam(value = "period") Integer period,
                              @RequestParam(value = "start_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
                              @RequestParam(value = "end_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
                              HttpServletResponse response) {
        PeriodChartQuery periodChartQuery = new PeriodChartQuery(projectId, fieldId, filterType, current, startTime, endTime, period);
        PeriodChartParam periodChartParam = periodChartQuery.getPeriodChartParam();
        String errorMessage = ChartValid.validViewpointEvaluationTopParam(periodChartParam);
        if (Validator.isNotNull(errorMessage)) {
            ChartUtil.excelErrorResponse(response, 4, errorMessage, Constants.TXTANLS_MODEL_NAME);
            return;
        }
        ServiceResult<ViewpointTopDTO> serviceResult = chartService.viewpointTop(periodChartParam);
        List<List<Object>> excelData = ChartExportConvert.viewpointTopToExcelData(serviceResult.getData());
        try {
            response.setContentType(Constants.EXCEL_CONTENT_TYPE);
            String fileName = URLEncoder.encode(ChartExportConvert.VIEWPOINT_TOP_FILE_NAME, Constants.UTF_8);
            response.setHeader(ChartExportConvert.EXCEL_RESPONSE_HEADER_KEY, String.format(ChartExportConvert.EXCEL_RESPONSE_HEADER_VALUE, fileName));
            EasyExcelFactory.write(response.getOutputStream()).autoCloseStream(Boolean.FALSE).sheet().doWrite(excelData);
        } catch (Exception e) {
            log.error("[Txtanls] 图表观点top5导出失败: 参数:{}", periodChartParam, e);
            ChartUtil.excelErrorResponse(response, 5, "图表观点top5统计导出失败", Constants.TXTANLS_MODEL_NAME);
        }
    }

    @ApiOperation(value = "话题提及率变化")
    @GetMapping(value = "/topic_reference")
    public void topicReference(@RequestParam(value = "project_id") String projectId,
                               @RequestParam(value = "field_id", required = false) String fieldId,
                               @RequestParam(value = "dtfiltertype", required = false) String filterType,
                               @RequestParam(value = "current", required = false) String current,
                               @RequestParam(value = "start_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
                               @RequestParam(value = "end_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
                               @RequestParam(value = "topics_group_id", required = false) String topicGid,
                               @RequestParam(value = "sort", required = false) String sortKey,
                               @RequestParam(value = "topics_type", required = false) String topicType,
                               HttpServletResponse response) {
        TopicReferenceQuery topicReferenceQuery = new TopicReferenceQuery(projectId, fieldId, filterType, current, startTime, endTime, topicGid, topicType, sortKey);
        TopicReferenceParam topicReferenceParam = topicReferenceQuery.getTopicReferenceParam();
        String errorMessage = ChartValid.validTopicReferenceParam(topicReferenceParam);
        if (Validator.isNotNull(errorMessage)) {
            ChartUtil.excelErrorResponse(response, 4, errorMessage, Constants.TXTANLS_MODEL_NAME);
            return;
        }
        ServiceResult<TopicReferenceRateDTO> serviceResult = chartService.statTopicReference(topicReferenceParam);
        List<List<Object>> excelData = ChartExportConvert.topicReferenceRateToExcelData(serviceResult.getData(), topicReferenceQuery.getInterval().getIndex());
        try {
            response.setContentType(Constants.EXCEL_CONTENT_TYPE);
            String fileName = URLEncoder.encode(ChartExportConvert.TOPIC_REFERENCE_FILE_NAME, Constants.UTF_8);
            response.setHeader(ChartExportConvert.EXCEL_RESPONSE_HEADER_KEY, String.format(ChartExportConvert.EXCEL_RESPONSE_HEADER_VALUE, fileName));
            EasyExcelFactory.write(response.getOutputStream()).autoCloseStream(Boolean.FALSE).sheet().doWrite(excelData);
        } catch (Exception e) {
            log.error("[Txtanls] 图表话题提及率变化导出失败: 参数:{}", topicReferenceParam, e);
            ChartUtil.excelErrorResponse(response, 5, "图表话题提及率变化导出失败", Constants.TXTANLS_MODEL_NAME);
        }
    }

    @ApiOperation(value = "观点评价变化")
    @GetMapping(value = "/viewpoint_evaluate")
    public void viewpointEvaluate(@RequestParam(value = "project_id") String projectId,
                                  @RequestParam(value = "field_id", required = false) String fieldId,
                                  @RequestParam(value = "dtfiltertype", required = false) String filterType,
                                  @RequestParam(value = "current", required = false) String current,
                                  @RequestParam(value = "start_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
                                  @RequestParam(value = "end_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
                                  @RequestParam(value = "view_group_id", required = false) String viewpointGid,
                                  @RequestParam(value = "sort", required = false) String sortKey,
                                  @RequestParam(value = "view_type", required = false) String viewpointType,
                                  @RequestParam(value = "comment_type", required = false) String evaluationType,
                                  HttpServletResponse response) {
        ViewpointEvaluateQuery viewpointEvaluateQuery = new ViewpointEvaluateQuery(projectId, fieldId, filterType, current, startTime, endTime, viewpointGid, sortKey, viewpointType, evaluationType);
        ViewpointEvaluateParam viewpointEvaluateParam = viewpointEvaluateQuery.getViewpointEvaluateParam();
        String errorMessage = ChartValid.validViewpointEvaluateParam(viewpointEvaluateParam);
        if (Validator.isNotNull(errorMessage)) {
            ChartUtil.excelErrorResponse(response, 4, errorMessage, Constants.TXTANLS_MODEL_NAME);
            return;
        }
        ServiceResult<ViewPointEvaluateDTO> serviceResult = chartService.statViewpointEvaluate(viewpointEvaluateParam);
        List<List<Object>> excelData = ChartExportConvert.viewPointEvaluateToExcelData(serviceResult.getData(), viewpointEvaluateQuery.getInterval().getIndex());
        try {
            response.setContentType(Constants.EXCEL_CONTENT_TYPE);
            String fileName = URLEncoder.encode(ChartExportConvert.VIEWPOINT_EVALUATE_FILE_NAME, Constants.UTF_8);
            response.setHeader(ChartExportConvert.EXCEL_RESPONSE_HEADER_KEY, String.format(ChartExportConvert.EXCEL_RESPONSE_HEADER_VALUE, fileName));
            EasyExcelFactory.write(response.getOutputStream()).autoCloseStream(Boolean.FALSE).sheet().doWrite(excelData);
        } catch (Exception e) {
            log.error("[Txtanls] 图表观点评价变化导出失败: 参数:{}", viewpointEvaluateParam, e);
            ChartUtil.excelErrorResponse(response, 5, "图表观点评价变化导出失败", Constants.TXTANLS_MODEL_NAME);
        }
    }

    @ApiOperation(value = "词云图")
    @GetMapping(value = "/word_cloud")
    public void wordCloud(@RequestParam(value = "project_id") String projectId,
                          @RequestParam(value = "field_id", required = false) String fieldId,
                          @RequestParam(value = "dtfiltertype", required = false) String filterType,
                          @RequestParam(value = "current", required = false) String current,
                          @RequestParam(value = "start_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
                          @RequestParam(value = "end_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
                          @RequestParam(value = "topicId", required = false) String topicId,
                          HttpServletResponse response) {
        WorkCloudQuery workCloudQuery = new WorkCloudQuery(projectId, fieldId, filterType, current, startTime, endTime, topicId);
        WorkCloudParam workCloudParam = workCloudQuery.getWorkCloudParam();
        String errorMessage = ChartValid.validWorkCloudParam(workCloudParam);
        if (Validator.isNotNull(errorMessage)) {
            ChartUtil.excelErrorResponse(response, 4, errorMessage, Constants.TXTANLS_MODEL_NAME);
            return;
        }
        ServiceResult<List<WorkCloudDataDTO>> serviceResult = chartService.statKeyword(workCloudParam);
        List<List<Object>> excelData = ChartExportConvert.workCloudDataToExcelData(serviceResult.getData());
        try {
            response.setContentType(Constants.EXCEL_CONTENT_TYPE);
            String fileName = URLEncoder.encode(ChartExportConvert.WORD_CLOUD_FILE_NAME, Constants.UTF_8);
            response.setHeader(ChartExportConvert.EXCEL_RESPONSE_HEADER_KEY, String.format(ChartExportConvert.EXCEL_RESPONSE_HEADER_VALUE, fileName));
            EasyExcelFactory.write(response.getOutputStream()).autoCloseStream(Boolean.FALSE).sheet().doWrite(excelData);
        } catch (Exception e) {
            log.error("[Txtanls] 图表词云图导出失败: 参数:{}", workCloudParam, e);
            ChartUtil.excelErrorResponse(response, 5, "图表词云图导出失败", Constants.TXTANLS_MODEL_NAME);
        }
    }

    @ApiOperation(value = "话题关联分析")
    @GetMapping(value = "/topic_relation")
    public void topicRelation(@RequestParam(value = "project_id") String projectId,
                              @RequestParam(value = "field_id", required = false) String fieldId,
                              @RequestParam(value = "dtfiltertype", required = false) String filterType,
                              @RequestParam(value = "current", required = false) String current,
                              @RequestParam(value = "start_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
                              @RequestParam(value = "end_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
                              @RequestParam(value = "topic_id", required = false) String topicId,
                              HttpServletResponse response) {
        TopicRelationQuery topicRelationQuery = new TopicRelationQuery(projectId, fieldId, filterType, current, startTime, endTime, topicId);
        TopicRelationParam topicRelationParam = topicRelationQuery.getTopicRelationParam();
        String errorMessage = ChartValid.validTopicRelationParam(topicRelationParam);
        if (Validator.isNotNull(errorMessage)) {
            ChartUtil.excelErrorResponse(response, 4, errorMessage, Constants.TXTANLS_MODEL_NAME);
            return;
        }
        ServiceResult<List<TopicRelationDTO>> serviceResult = chartService.statTopicRelation(topicRelationParam);
        List<List<Object>> excelData = ChartExportConvert.topicRelationToExcelData(serviceResult.getData());
        try {
            response.setContentType(Constants.EXCEL_CONTENT_TYPE);
            String fileName = URLEncoder.encode(ChartExportConvert.TOPIC_RELATION_FILE_NAME, Constants.UTF_8);
            response.setHeader(ChartExportConvert.EXCEL_RESPONSE_HEADER_KEY, String.format(ChartExportConvert.EXCEL_RESPONSE_HEADER_VALUE, fileName));
            EasyExcelFactory.write(response.getOutputStream()).autoCloseStream(Boolean.FALSE).sheet().doWrite(excelData);
        } catch (Exception e) {
            log.error("[Txtanls] 图表话题关联分析导出失败: 参数:{}", topicRelationParam, e);
            ChartUtil.excelErrorResponse(response, 5, "图表话题关联分析导出失败", Constants.TXTANLS_MODEL_NAME);
        }
    }

    @ApiOperation(value = "话题分析")
    @GetMapping(value = "/topic_analysis")
    public void topicAnalysis(@RequestParam(value = "project_id") String projectId,
                              @RequestParam(value = "field_id", required = false) String fieldId,
                              @RequestParam(value = "dtfiltertype", required = false) String filterType,
                              @RequestParam(value = "current", required = false) String current,
                              @RequestParam(value = "start_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
                              @RequestParam(value = "end_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
                              @RequestParam(value = "period", required = false) Integer period,
                              HttpServletResponse response) {

        PeriodChartQuery periodChartQuery = new PeriodChartQuery(projectId, fieldId, filterType, current, startTime, endTime, period);
        PeriodChartParam periodChartParam = periodChartQuery.getPeriodChartParam();
        String errorMessage = ChartValid.validViewpointEvaluationTopParam(periodChartParam);
        if (Validator.isNotNull(errorMessage)) {
            ChartUtil.excelErrorResponse(response, 4, errorMessage, Constants.TXTANLS_MODEL_NAME);
            return;
        }
        ServiceResult<TopicAnalysisDTO> serviceResult = chartService.statTopicAnalysis(periodChartParam);
        List<List<Object>> excelData = ChartExportConvert.topicAnalysisToExcelData(serviceResult.getData());
        try {
            response.setContentType(Constants.EXCEL_CONTENT_TYPE);
            String fileName = URLEncoder.encode(ChartExportConvert.TOPIC_ANALYSIS_FILE_NAME, Constants.UTF_8);
            response.setHeader(ChartExportConvert.EXCEL_RESPONSE_HEADER_KEY, String.format(ChartExportConvert.EXCEL_RESPONSE_HEADER_VALUE, fileName));
            EasyExcelFactory.write(response.getOutputStream()).autoCloseStream(Boolean.FALSE).sheet().doWrite(excelData);
        } catch (Exception e) {
            log.error("[Txtanls] 图表话题提及率变化趋势导出失败: 参数:{}", periodChartQuery, e);
            ChartUtil.excelErrorResponse(response, 5, "图表话题提及率变化趋势导出失败", Constants.TXTANLS_MODEL_NAME);
        }
    }

    @ApiOperation(value = "话题提及率变化趋势")
    @GetMapping(value = "/topic_reference_trend")
    public void topicReferenceTrend(@RequestParam(value = "project_id") String projectId,
                                    @RequestParam(value = "field_id", required = false) String fieldId,
                                    @RequestParam(value = "dtfiltertype", required = false) String filterType,
                                    @RequestParam(value = "current", required = false) String current,
                                    @RequestParam(value = "start_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
                                    @RequestParam(value = "end_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
                                    @RequestParam(value = "topics_group_id", required = false) String topicGid,
                                    @RequestParam(value = "topics_id", required = false) String topicId,
                                    HttpServletResponse response) {
        TopicReferenceTrendQuery topicReferenceTrendQuery = new TopicReferenceTrendQuery(projectId, fieldId, filterType, current, startTime, endTime, topicGid, topicId);
        TopicReferenceTrendParam topicReferenceTrendParam = topicReferenceTrendQuery.getTopicReferenceTrendParam();
        String errorMessage = ChartValid.validTopicReferenceTrendParam(topicReferenceTrendParam);
        if (Validator.isNotNull(errorMessage)) {
            ChartUtil.excelErrorResponse(response, 4, errorMessage, Constants.TXTANLS_MODEL_NAME);
            return;
        }
        ServiceResult<List<TopicStatDTO>> serviceResult = chartService.statTopicReferenceTrend(topicReferenceTrendParam);
        List<List<Object>> excelData = ChartExportConvert.topicStatToExcelData(serviceResult.getData(), topicReferenceTrendQuery.getInterval().getIndex());
        // 导出时需要统计的观点名称，所以需要在controller查询
        String statId = Validator.isNotEmpty(topicReferenceTrendParam.getTopicGid()) ? topicReferenceTrendParam.getTopicGid() : topicReferenceTrendParam.getTopicId();
        TopicDO topic = topicService.getById(statId);
        if (Validator.isNull(topic)) {
            log.error("[Txtanls] 图表话题提及率变化趋势导出失败，没有找到{}对应的话题", statId);
            ChartUtil.excelErrorResponse(response, 5, String.format("图表话题提及率变化趋势导出失败，没有找到%s对应的话题", statId), Constants.TXTANLS_MODEL_NAME);
            return;
        }
        try {
            response.setContentType(Constants.EXCEL_CONTENT_TYPE);
            String fileName = URLEncoder.encode(ChartExportConvert.TOPIC_REFERENCE_TREND_FILE_NAME.replace(Constants.CHART_NAME, topic.getName()), Constants.UTF_8);
            response.setHeader(ChartExportConvert.EXCEL_RESPONSE_HEADER_KEY, String.format(ChartExportConvert.EXCEL_RESPONSE_HEADER_VALUE, fileName));
            EasyExcelFactory.write(response.getOutputStream()).autoCloseStream(Boolean.FALSE).sheet().doWrite(excelData);
        } catch (Exception e) {
            log.error("[Txtanls] 图表话题提及率变化趋势导出失败: 参数:{}", topicReferenceTrendParam, e);
            ChartUtil.excelErrorResponse(response, 5, "图表话题提及率变化趋势导出失败", Constants.TXTANLS_MODEL_NAME);
        }
    }

    @ApiOperation(value = "观点情感分布变化")
    @GetMapping(value = "/viewpoint_evaluate_trend")
    public void viewpointEvaluateTrend(@RequestParam(value = "project_id") String projectId,
                                       @RequestParam(value = "field_id", required = false) String fieldId,
                                       @RequestParam(value = "dtfiltertype", required = false) String filterType,
                                       @RequestParam(value = "current", required = false) String current,
                                       @RequestParam(value = "start_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
                                       @RequestParam(value = "end_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
                                       @RequestParam(value = "view_id", required = false) String viewId,
                                       @RequestParam(value = "view_group_id", required = false) String viewGid,
                                       HttpServletResponse response) {
        ViewpointEvaluateTrendQuery viewpointEvaluateTrendQuery = new ViewpointEvaluateTrendQuery(projectId, fieldId, filterType, current, startTime, endTime, viewGid, viewId);
        ViewpointEvaluateTrendParam viewpointEvaluateTrendParam = viewpointEvaluateTrendQuery.getViewpointEvaluateTrendParam();
        String errorMessage = ChartValid.validViewpointEvaluateTrendParam(viewpointEvaluateTrendParam);
        if (Validator.isNotNull(errorMessage)) {
            ChartUtil.excelErrorResponse(response, 4, errorMessage, Constants.TXTANLS_MODEL_NAME);
            return;
        }
        ServiceResult<List<ViewpointEvaluateStatDTO>> serviceResult = chartService.statViewpointEvaluateTrend(viewpointEvaluateTrendParam);
        // 是否是观点组
        boolean isGroup = Validator.isNotEmpty(viewGid);
        List<List<Object>> excelData = ChartExportConvert.viewpointEvaluateStatToExcelData(serviceResult.getData(), viewpointEvaluateTrendQuery.getInterval().getIndex(), isGroup);
        // 导出时需要统计的观点名称，所以需要在controller查询
        String statId = Validator.isNotEmpty(viewpointEvaluateTrendParam.getViewGid()) ? viewpointEvaluateTrendParam.getViewGid() : viewpointEvaluateTrendParam.getViewId();
        ViewpointDO viewpoint = viewpointService.getById(statId);
        if (Validator.isNull(viewpoint)) {
            log.error("[Txtanls] 图表观点情感分布变化导出失败，没有找到{}对应的观点", statId);
            ChartUtil.excelErrorResponse(response, 5, String.format("图表观点情感分布变化导出失败，没有找到%s对应的观点", statId), Constants.TXTANLS_MODEL_NAME);
            return;
        }
        try {
            response.setContentType(Constants.EXCEL_CONTENT_TYPE);
            String fileName = URLEncoder.encode(ChartExportConvert.VIEWPOINT_EVALUATE_TREND_FILE_NAME.replace(Constants.CHART_NAME, viewpoint.getViewContent()), Constants.UTF_8);
            response.setHeader(ChartExportConvert.EXCEL_RESPONSE_HEADER_KEY, String.format(ChartExportConvert.EXCEL_RESPONSE_HEADER_VALUE, fileName));
            EasyExcelFactory.write(response.getOutputStream()).autoCloseStream(Boolean.FALSE).sheet().doWrite(excelData);
        } catch (Exception e) {
            log.error("[Txtanls] 图表观点情感分布变化导出失败: 参数:{}", viewpointEvaluateTrendParam, e);
            ChartUtil.excelErrorResponse(response, 5, "图表观点情感分布变化导出失败", Constants.TXTANLS_MODEL_NAME);
        }
    }
}
